/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.server.i18n;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import com.niiuzu.server.util.LocaleUtil;
import com.niiuzu.shared.model.ClientContext;

/**
 * Gestionnaires des ressources d'internationalisation côté serveur.
 */
public class ServerI18nMessages {

	/**
	 * Bundles disponibles côté serveur.
	 */
	public enum Bundle {
		ErrorMessages, MailMessages
	}

	private ResourceBundle resourceBundle;

	/**
	 * Construit une nouvelle instance de {@link ServerI18nMessages}.
	 * 
	 * @param bundle
	 *            lot de messages.
	 * @param context
	 *            contexte de la partie cliente.
	 */
	public ServerI18nMessages(Bundle bundle, ClientContext context) {
		this(bundle, LocaleUtil.getLocale(context.getLocale()));
	}

	/**
	 * Construit une nouvelle instance de {@link ServerI18nMessages}.
	 * 
	 * @param bundle
	 *            lot de messages.
	 * @param locale
	 *            localisation permettant d'internationaliser les messages
	 *            retournés
	 */
	public ServerI18nMessages(Bundle bundle, Locale locale) {

		StringBuilder bundleName = new StringBuilder();
		bundleName.append(getClass().getPackage().getName());
		bundleName.append(".");
		bundleName.append(bundle.name());

		resourceBundle = ResourceBundle.getBundle(bundleName.toString(),
				(locale != null ? locale : Locale.getDefault()));
	}

	/**
	 * Récupère le message internationalisée correspondant à la clef.
	 * 
	 * @see #getMessage(String, Object...)
	 */
	public String getMessage(String key) {
		return getMessage(key, new Object[] {});
	}

	/**
	 * Récupère le message internationalisée en y injectant les arguments.
	 * 
	 * @param key
	 *            clef identifiant du message.
	 * @param args
	 *            liste des arguments injectés dans le message.
	 * @return message correspondant à la clef et contenant les arguments.
	 */
	public String getMessage(String key, Object... args) {
		String message = resourceBundle.getString(key);
		if (args != null && args.length > 0) {
			message = MessageFormat.format(message, args);
		}
		return message;
	}
}
